package com.zzyl.service.impl;

import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private WechatService wechatService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 获取openId
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());
        // 获取手机号
        String phone = wechatService.getPhoneCode(userLoginRequestDto.getPhoneCode());

        // 根据openId查询用户
        Member member = memberMapper.selectByOpenId(openId);
        //

        if (ObjectUtil.isEmpty(member)) {

            member = new Member();
            member.setOpenId(openId);
            member.setName("小于帅不自知");
            member.setPhone(phone);
            memberMapper.insert(member);
        } else {
            if(ObjectUtil.equals(member.getPhone(), phone)) {
                member.setPhone(phone);
                memberMapper.update(member);
            }
        }

        Map<String, Object> params = new HashMap<>();
        params.put(Constants.JWT_USERID, member.getId());
        params.put(Constants.JWT_USERNAME, member.getName());

        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), params);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getName());
        return loginVo;
    }
}
